﻿import cgi
import os 
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp                                        
from google.appengine.ext.webapp.util import run_wsgi_app                      
import logging                                                                 
 
from StringIO import StringIO                                                  
import traceback
import simplejson
import xmlrpclib
from xmlrpcserver import XmlRpcServer
from google.appengine.api import users
from entities import *
from datetime import date
import datetime

class Application:
    def __init__(self):
        pass                    
        
    def getGreeting(self,meta):  
        greetings = db.GqlQuery("SELECT * FROM Greeting ORDER BY date DESC LIMIT 10")
        greetlist = []
        for greeting in  greetings:
            greetdict ={}
            greetdict['content'] = greeting.content 
            greetdict['date'] = greeting.date
            greetlist.append(greetdict)
        tuple_greetlist = tuple(greetlist)
        xmlrpccall = xmlrpclib.dumps(tuple_greetlist, 'GetAllGreeting')
        return xmlrpccall

    def getGenre(self,meta):
        test= [{'job': 'student', 'name': 'Long'}, {'job': 'student', 'name': 'An dam'}]
        tuple_test = tuple(test)
        
        xmlrpccall = xmlrpclib.dumps(tuple_test, 'GetAllGreeting')
        return xmlrpccall
        #return test
      
    def getName(self,meta,nameGenre, num):
        #genre = db.GqlQuery("SELECT * FROM Genre WHERE name = :1", nameGenre)
        num = int(num) + 2  
        return "Bạn vừa đánh vào chữ " + nameGenre + "số đã thêm 2 là:" + str(num)

    #-----------------------------
    #-LinhVuc
    #-----------------------------

    def getAllLinhVuc(self,meta,keyNguoiDung):
        result = LinhVucEntities.GetAll(keyNguoiDung)
        #result = LinhVuc.Test()
        xmlrpccall = xmlrpclib.dumps(result, 'GetAllLinhVuc')
        return xmlrpccall

        
    def addLinhVuc(self, meta, key, LinhVucID):
        #u_TenLinhVuc = unicode(TenLinhVuc, 'utf-8')
        result = LinhVucEntities.Add(key, LinhVucID)
        return result
    
    def getLinhVuc(self, meta, keyNguoiDung, LinhVucID):
        result = LinhVucEntities.Get(keyNguoiDung, LinhVucID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetLinhVuc')
        return xmlrpccall
        
    def deleteLinhVuc(self, meta, keyNguoiDung, LinhVucID):
        result = LinhVucEntities.Delete(keyNguoiDung, LinhVucID)
        return result
        
    #-----------------------------
    #-NganhNghe
    #-----------------------------
    def getNganhNghe(self, meta, keyNguoiDung, LinhVucID, NganhNgheID):
        result = NganhNgheEntities.Get(keyNguoiDung,LinhVucID, NganhNgheID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetNganhNghe')
        return xmlrpccall        
    
    def getAllNganhNghe(self, meta, keyNguoiDung, LinhVucID):
        result = NganhNgheEntities.GetAll(keyNguoiDung,LinhVucID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetAllNganhNghe')
        return xmlrpccall  
    
    def addNganhNghe(self, meta, keyNguoiDung, NganhNgheID):
        result = NganhNgheEntities.Add(keyNguoiDung,NganhNgheID)
        return result    
        
    def deleteNganhNghe(self, meta, keyNguoiDung, NganhNgheID):
        result = NganhNgheEntities.Delete(keyNguoiDung,NganhNgheID)
        return result  
        
    #------------------------------------------
    #- DoiTuong
    #------------------------------------------
    
    def getDoiTuong(self, meta, keyNguoiDung, DoiTuongID):
        result = DoiTuongEntities.Get(keyNguoiDung,DoiTuongID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetDoiTuong')
        return xmlrpccall        
    
    def getAllDoiTuong(self, meta, keyNguoiDung):
        result = DoiTuongEntities.GetAll(keyNguoiDung)
        xmlrpccall = xmlrpclib.dumps(result, 'GetAllDoiTuong')
        return xmlrpccall  

    def addDoiTuong(self, meta, keyNguoiDung, DoiTuongID):
        result = DoiTuongEntities.Add(keyNguoiDung,DoiTuongID)
        return result         
    
    def deleteDoiTuong(self, meta, keyNguoiDung, DoiTuongID):
        result = DoiTuongEntities.Delete(keyNguoiDung,DoiTuongID)
        return result         
    
    #------------------------------------------
    #- NhaTuyenDung
    #------------------------------------------    
    def getNhaTuyenDungRadian(self, meta, lat, lng, radian):
        result = NhaTuyenDungEntities.GetViTriRadian(float(lat), float(lng), float(radian))
        xmlrpccall = xmlrpclib.dumps(result, 'GetNhaTuyenDungRadian')
        return xmlrpccall
        
    # Kinh nghiem xuong mau : cai nay ko truyen duoc doi tuong text :(, phai doi ve string.    
    def getNhaTuyenDung(self,meta,keyNguoiDung,TenThuongHieu,Email,TrangThaiID, QuiMoID, LinhVucID, NhaTuyenDungID):
        result = NhaTuyenDungEntities.Get(keyNguoiDung,unicode(TenThuongHieu), Email,TrangThaiID, QuiMoID, LinhVucID, NhaTuyenDungID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetNhaTuyenDung')
        return xmlrpccall


        
        #return result
    def addNhaTuyenDung(self,meta, keyNguoiDung, TenThuongHieu, MieuTa, Email, SoDienThoai, LinhVucID, NguoiLienHe, QuiMoID, AnhDaiDien,  Website, ViTriText, lat, lng, NguoiDungID):
        ViTri = db.GeoPt(lat=float(lat), lon=float(lng))
        TrangThaiID = TrangThaiEntities.GetID(Entities.GetKey(),u'Vừa nhập');
        result = NhaTuyenDungEntities.AddService(keyNguoiDung,TenThuongHieu, MieuTa, Email, SoDienThoai, LinhVucID, NguoiLienHe, QuiMoID, AnhDaiDien,  Website, ViTriText, ViTri, TrangThaiID, NguoiDungID)
        return result
    
    def updateNhaTuyenDung(self,meta,keyNguoiDung, NhaTuyenDungID, TenThuongHieu, MieuTa, SoDienThoai, LinhVucID, NguoiLienHe, QuiMoID, AnhDaiDien, Website, ViTriText, lat, lng):
        result = NhaTuyenDungEntities.UpdateService(keyNguoiDung, NhaTuyenDungID, TenThuongHieu, MieuTa, SoDienThoai, LinhVucID, NguoiLienHe, QuiMoID, AnhDaiDien, Website, ViTriText, lat, lng)
        return result
    
    def deleteNhaTuyenDung(self, meta, keyNguoiDung, NhaTuyenDungID):
        return NhaTuyenDungEntities.Delete(keyNguoiDung, NhaTuyenDungID)
    
    def getCompany(self, meta, lat, lon, rad):
        test= [{'company': 'FPT', 'phone': '01663355355','location':'21.034797 105.770187'},
               {'company': 'Chua Boc', 'phone': '01663335252','location':'21.009319 105.824089'},
               {'company': 'Ho Tay company', 'phone': '01363335252','location':'21.064115 105.823917'}]
        tuple_test = tuple(test)
        
        xmlrpccall = xmlrpclib.dumps(tuple_test, 'GetCompany')
        return xmlrpccall
        #return tuple_test
    #-----------------------------------------
    #- DonDangTuyen
    #-----------------------------------------
    def updateTrangThaiDonDangTuyen(self, meta, DonDangTuyenID, TrangThaiID):
        result = DonDangTuyenEntities.UpdateStatus(DonDangTuyenID, TrangThaiID)
        return result
        
    def updateTenTrangThaiDonDangTuyen(self, meta,keyNguoiDung, DonDangTuyenID, TenTrangThai):
        result = DonDangTuyenEntities.UpdateTrangThai(keyNguoiDung, DonDangTuyenID, unicode(TenTrangThai))
        return result
        
    def addDonDangTuyen(self, meta, keyNguoiDung, NgayKetThuc, MieuTa, YeuCau, NhaTuyenDungID, NganhNgheID, ChucDanh, MucLuongID, LoaiHinhID, TinhThanhID, CapBacID):
        NgayDang = datetime.datetime.now()
        TrangThaiID = TrangThaiEntities.GetID(Entities.GetKey(),u'Vừa nhập');
        result = DonDangTuyenEntities.AddWithOutDoiTuong(keyNguoiDung, NgayDang, NgayKetThuc, MieuTa, YeuCau, NhaTuyenDungID, NganhNgheID, ChucDanh,MucLuongID, LoaiHinhID, TinhThanhID, CapBacID, TrangThaiID)
        return result
        
    def addDonDangTuyenDoiTuong(self, meta, keyNguoiDung, DonDangTuyenID, DoiTuongID):
        result = DangTuyenDoiTuongEntities.Add(keyNguoiDung, int(DonDangTuyenID), int(DoiTuongID))
        return result
        
    def getDonDangTuyenDoiTuong(self, meta, keyNguoiDung, DonDangTuyenID, DoiTuongID):
        result = DangTuyenDoiTuongEntities.Get(keyNguoiDung, int(DonDangTuyenID), int(DoiTuongID))
        xmlrpccall = xmlrpclib.dumps(result, 'GetDonDangTuyenDoiTuong')
        return xmlrpccall
        
    def deleteDonDangTuyenDoiTuong(self, meta, keyNguoiDung, DonDangTuyenID, DoiTuongID):
        result = DangTuyenDoiTuongEntities.Delete(keyNguoiDung, int(DonDangTuyenID), int(DoiTuongID))
        return result    
        
    def deleteDonDangTuyen(self, meta, keyNguoiDung, DonDangTuyenID):
        result = DonDangTuyenEntities.Delete(keyNguoiDung, int(DonDangTuyenID))
        return result         
    
    def getDonDangTuyen(self, meta, keyNguoiDung, NhaTuyenDungID, DonDangTuyenID, txtSearch, NgayDang, NgayKetThuc, TinhThanhID , CapBacID , TrangThaiID, MucLuongID,LoaiHinhID, LinhVucID, NganhNgheID, DoiTuongID):
        result = DonDangTuyenEntities.GetService(keyNguoiDung, NhaTuyenDungID, DonDangTuyenID, unicode(txtSearch), NgayDang, NgayKetThuc, TinhThanhID , CapBacID , TrangThaiID, MucLuongID,LoaiHinhID, LinhVucID, NganhNgheID, DoiTuongID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetDonDangTuyen')
        return xmlrpccall        
 
    def getAllDonDangTuyen(self, meta, NhaTuyenDungID, DonDangTuyenID, txtSearch, NgayDang, NgayKetThuc, TinhThanhID , CapBacID , MucLuongID,LoaiHinhID, LinhVucID, NganhNgheID, DoiTuongID):
        TrangThaiID = TrangThaiEntities.GetID(Entities.GetKey(),u"Hợp lệ")
        result = DonDangTuyenEntities.All(NhaTuyenDungID, DonDangTuyenID, unicode(txtSearch), NgayDang, NgayKetThuc, TinhThanhID , CapBacID , TrangThaiID, MucLuongID,LoaiHinhID, LinhVucID, NganhNgheID, DoiTuongID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetAllDonDangTuyen')
        return xmlrpccall  
    def updateDonDangTuyen(self, meta, keyNguoiDung, DonDangTuyenID, NgayKT, MieuTa, YeuCau, NganhNgheID, ChucDanh,MucLuongID, LoaiHinhID, TinhThanhID, CapBacID):
        result = DonDangTuyenEntities.Update(keyNguoiDung,DonDangTuyenID, NgayKT, MieuTa, YeuCau, NganhNgheID, ChucDanh, MucLuongID, LoaiHinhID, TinhThanhID, CapBacID)
        return result
        
    def getQuiMo(self, meta, key, QuiMoID):
        result= QuiMoEntities.Get(key,QuiMoID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetQuiMo')
        return xmlrpccall       
        
    def getMucLuong(self, meta, key, MucLuongID):
        result= MucLuongEntities.Get(key, MucLuongID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetMucLuong')
        return xmlrpccall     
        
    def getTinhThanh(self, meta, key, TinhThanhID):
        result= TinhThanhEntities.Get(key, TinhThanhID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetTinhThanh')
        return xmlrpccall    
        
    def getLoaiHinh(self, meta, key, LoaiHinhID):
        result= LoaiHinhEntities.Get(key, LoaiHinhID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetLoaiHinh')
        return xmlrpccall      

    def getCapBac(self, meta, key, CapBacID):
        result= CapBacEntities.Get(key, CapBacID)
        xmlrpccall = xmlrpclib.dumps(result, 'GetCapBac')
        return xmlrpccall

    def getTrangThai(self, meta, key, TrangThaiID,TenTrangThai):
        result= TrangThaiEntities.Get(key, TrangThaiID,unicode(TenTrangThai))
        xmlrpccall = xmlrpclib.dumps(result, 'GetTrangThai')
        return xmlrpccall  

            
#-----------------------------------------
#- webservice XMLRPC
#-----------------------------------------

class XMLRpcHandler(webapp.RequestHandler):                                    
    rpcserver = None
                                
    def __init__(self):         
        self.rpcserver = XmlRpcServer()                                        
        app = Application()                                                    
        self.rpcserver.register_class('app',app)                               
                                                                               
    def post(self):
        request = StringIO(self.request.body)
        request.seek(0)                                                        
        response = StringIO()                                                  
        try:
            self.rpcserver.execute(request, response, None)                    
        except Exception, e:                                                   
            logging.error('Error executing: '+str(e))                          
            for line in traceback.format_exc().split('\n'):                    
                logging.error(line)
        finally:
            response.seek(0)  
                                                                               
        rstr = response.read()                                                 
        self.response.headers['Content-type'] = 'text/xml'                     
        self.response.headers['Content-length'] = "%d"%len(rstr)               
        self.response.out.write(rstr)
